/*
 * @Author: xiaosihan 
 * @Date: 2023-08-10 11:24:00 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-12-22 00:38:53
 */

import designEditor from "@/editorComponent/designEditor";
import editorStore from "@/editorComponent/editorStore";
import { Input, Slider } from "antd";
import clsx from "clsx";
import { clamp, throttle } from "lodash";
import { autorun } from "mobx";
import { useEffect, useRef, useState } from "react";
import styles from "./toolFontBend.module.less";
import FabricText from "@/myFabric/FabricText";
import nameNumStore from "@/editorComponent/LeftMenu/NameNum/nameNumStore";


// 文字弯曲
export default function ToolFontBend() {

  const [visible, setVisible] = useState(false);
  const [disable, setDisable] = useState(false);
  const [bendDegree, setBendDegree] = useState(editorStore.bendDegree);

  useEffect(() => autorun(() => {
    const { activeObjectId, bendDegree, lock } = editorStore;
    const { step } = nameNumStore;
    const activeObject = designEditor.fabricCanvas.getActiveObject();
    if (activeObjectId && activeObject && activeObject.type === "i-text") {
      const lockNameNum = (["name", "num"].includes(activeObject.name || "") && step === 3);
      setDisable(lock || lockNameNum);
      setBendDegree(bendDegree);
      setVisible(true);
    } else {
      setVisible(false);
    }
  }), []);

  useEffect(() => autorun(() => {
    setBendDegree(editorStore.bendDegree);
  }), []);

  const activeObjectBendDegree = throttle((bendDegree: number) => {
    const activeObject = designEditor.fabricCanvas.getActiveObject();
    if (activeObject) {
      (activeObject as FabricText).set("bendDegree", bendDegree);
      designEditor.render();
    }
  }, 30);

  return (
    <div
      className={clsx(styles.toolFontBend, visible && styles.visible, disable && styles.disable)}
    >
      <span className={styles.lable} >弯曲</span>
      <Slider
        className={styles.slider}
        min={0}
        max={360}
        value={bendDegree}
        onChange={v => {
          activeObjectBendDegree(v);
          editorStore.setBendDegree(v);
        }}
      />
      <Input
        key={bendDegree}
        className={styles.input}
        defaultValue={bendDegree}
        onPressEnter={e => {
          const v = Number((e.target as HTMLInputElement).value);
          activeObjectBendDegree(v);
          editorStore.setBendDegree(v);
        }}
        onBlur={e => {
          const v = Number((e.target as HTMLInputElement).value);
          activeObjectBendDegree(v);
          editorStore.setBendDegree(v);
        }}
        onWheel={e => {
          const value = clamp((bendDegree - Math.sign(e.deltaY)), 1, 1000);
          activeObjectBendDegree(value);
          editorStore.setBendDegree(value);
        }}
      />
    </div>
  );

}